import 'dart:convert';
import 'dart:io';

class FindServer {
  RawDatagramSocket _clientSocket;

  Future<bool> run() async {
    try {
      if (_clientSocket == null) {
        var ips = await InternetAddress.lookup(Platform.localHostname,
            type: InternetAddressType.IPv4);
        print(ips);
        _clientSocket = await RawDatagramSocket.bind(InternetAddress.anyIPv4, 34343);
      }
      linten();
      sayHello();
      return true;
    } catch (e) {
      print(e.toString());
      return false;
    }
  }

  Future sayHello() async {
    var hello = "hello world 主机A";
    var helloBytes = Utf8Encoder().convert(hello);
    print(helloBytes.toList());

    Future.doWhile(() async {
      await Future.delayed(Duration(seconds: 10));
      _clientSocket.broadcastEnabled = true;
      _clientSocket.send(helloBytes, InternetAddress("255.255.255.255"), 34343);
      return true;
    });
  }

  linten() async {
    try {
      await for (var event in _clientSocket.asBroadcastStream()) {
      if (RawSocketEvent.read == event) {
        var data = _clientSocket.receive();
        var result = Utf8Codec().decode(data.data);
        print([result, data.address, data.port]);
      }
      print(event);
    }
    } catch (e) {
      print(e.toString());
    }

  }
}
